<script>
import { Lock, UserFilled } from "@element-plus/icons-vue";
import request from "../utils/request";
import { ElMessage } from "element-plus";
import { setCookie, getCookie, eraseCookie } from "@/utils/cookie";
import config from '@/config/config'
export default {
  name: "Login",
  computed: {
    UserFilled() {
      return UserFilled;
    },
    Lock() {
      return Lock;
    },
  },
  data() {
    return {
      form: {
        username: getCookie('username') || "",
        password: getCookie('password') || "",
        captcha: "",  // 新增验证码字段
      },
      captchaSrc: config.baseurl+"/api/captcha?" + new Date().getTime(), // 验证码图片的 URL
      rememberMe: !!getCookie('username'),
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    // 刷新验证码图片
    refreshCaptcha() {
      this.captchaSrc = config.baseurl+"/api/captcha?" + new Date().getTime();
    },
    async login() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          try {
            console.log("form:", this.form);
            const resManager = await request.post('/manager/login', this.form);
            if (resManager.code === 0) {
              this.handleLoginSuccess(resManager.data);
              this.$router.push('/home'); // 跳转到重定向地址或首页
            } else {
              const resUser = await request.post('/users/login', this.form);
              if (resUser.code === 0) {
                this.handleLoginSuccess(resUser.data);
                this.$router.push('/house'); // 跳转到重定向地址或首页
              } else {
                ElMessage.error(resUser.msg);
                this.refreshCaptcha(); // 刷新验证码
              }
            }
          } catch (error) {
            ElMessage.error('登录失败，请重试');
            this.refreshCaptcha(); // 刷新验证码
          }
        }
      });
    },
    handleLoginSuccess(data) {
      this.$store.dispatch('login', data); // 存储 state
      if (this.rememberMe) {
        setCookie('username', this.form.username, 7); // 存储 7 天
        setCookie('password', this.form.password, 7); // 存储 7 天
      } else {
        eraseCookie('username');
        eraseCookie('password');
      }
      console.log("token:", data);
      ElMessage.success('登录成功');
    },
  },
};
</script>

<template>
  <div style="width:100%; height:100vh;background-color:darkslateblue; overflow: hidden">
    <div style="width: 400px;margin:200px auto">
      <div style="color:#cccccc; font-size:30px; text-align:center; padding:30px 0">欢迎登录</div>
      <el-form ref="form" :model="form" size="default" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="form.username" :prefix-icon="UserFilled" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" :prefix-icon="Lock" type="password" placeholder="请输入密码" show-password/>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input v-model="form.captcha" placeholder="请输入验证码"/>
          <img :src="captchaSrc" @click="refreshCaptcha" alt="captcha" style="cursor: pointer; margin-top: 10px;"/>
        </el-form-item>
        <el-form-item>
          <el-button style="width:100%" type="primary" @click="login">登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
</style>
